import React from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import * as Sentry from '@sentry/react';
import { CaptureConsole } from '@sentry/integrations';
import { store } from './redux/store';
import { HistoryProvider } from './contexts/HistoryContext';
import ErrorBoundary from './components/ErrorBoundary';
import App from './App';
import theme from './theme';
import '@metacell/geppetto-meta-ui/flex-layout/style/dark.css';

// Import styles
import './css/netpyne.less';
import './css/material.less';
import './css/traceback.less';
import './css/flexlayout.less';
import './css/tree.less';
import './layout/layout.css';
import './pages/form.css';
import './pages/frame8.css';
import './pages/scaffold.css';

// Initialize Geppetto configuration
declare global {
  interface Window {
    GEPPETTO_CONFIGURATION?: {
      notebookName?: string;
      [key: string]: any;
    };
    $?: any;
    GEPPETTO?: any;
    cores?: number;
    tuts?: string[];
  }

  namespace NodeJS {
    interface Global {
      GEPPETTO_CONFIGURATION?: any;
    }
  }

  const GEPPETTO_CONFIGURATION: any;
  const GEPPETTO: any;
}

const geppettoConfig = require('../GeppettoConfiguration.json');
(global as any).GEPPETTO_CONFIGURATION = geppettoConfig;
const { initGeppetto } = require('@metacell/geppetto-meta-client/GEPPETTO');

// Sentry error tracking - only enabled in production environment
if (process.env.NODE_ENV === 'production') {
  Sentry.init({
    dsn: 'https://d8bf7e40eec34cb9891f6dd8207b5e83@sentry.metacell.us/6',
    integrations: [
      new CaptureConsole({
        levels: ['error'],
      }),
    ],
    tracesSampleRate: 1.0,
  });
} else {
  console.log('开发模式运行中 - Sentry 已禁用');
}

// Temporary fix for Geppetto compatibility
window.$ = Array;

// Initialize Geppetto asynchronously (don't block page rendering)
// Use setTimeout to ensure React has rendered first
setTimeout(() => {
  try {
    initGeppetto();
  } catch (error) {
    console.warn('Geppetto initialization error:', error);
  }
}, 0);

// Get container element - try #root first, fallback to #mainContainer for compatibility
let container = document.querySelector('#root');
if (!container) {
  container = document.querySelector('#mainContainer');
}

if (!container) {
  throw new Error('Could not find #root or #mainContainer element');
}

// Set container styles
(container as HTMLElement).style.width = '100%';
(container as HTMLElement).style.height = '100vh';
(container as HTMLElement).style.margin = '0';
(container as HTMLElement).style.padding = '0';
(container as HTMLElement).style.overflow = 'auto';

// Set body and html styles
document.body.style.margin = '0';
document.body.style.padding = '0';
document.body.style.height = '100vh';
document.body.style.overflow = 'hidden';
document.documentElement.style.height = '100%';
document.documentElement.style.margin = '0';
document.documentElement.style.padding = '0';

// Hide the initial loading screen from HTML template (old style)
const loadingText = document.querySelector('#loadingText');
if (loadingText) {
  (loadingText as HTMLElement).style.display = 'none';
}

// Also hide footer if it exists (old style)
const footer = document.querySelector('#footer');
if (footer) {
  (footer as HTMLElement).style.display = 'none';
}

// Create root and render
const root = createRoot(container);

console.log('🚀 启动 React 应用...');
console.log('📍 容器:', container);
console.log('📍 容器 HTML:', container?.innerHTML?.substring(0, 100));

try {
  root.render(
    <React.StrictMode>
      <ErrorBoundary>
        <Provider store={store}>
          <ThemeProvider theme={theme}>
            <CssBaseline />
            <BrowserRouter>
              <HistoryProvider>
                <App />
              </HistoryProvider>
            </BrowserRouter>
          </ThemeProvider>
        </Provider>
      </ErrorBoundary>
    </React.StrictMode>
  );
  console.log('✅ React 应用渲染成功');
} catch (error) {
  console.error('❌ 应用渲染错误:', error);
  throw error;
}

// Set default Geppetto color
if (window.GEPPETTO?.Resources?.COLORS) {
  window.GEPPETTO.Resources.COLORS.DEFAULT = '#6f54aa';
}

